import {
  getCardDetails,
  getCardList
} from "../../apis/card";
import {
  groupQRcode
} from '../../apis/group'
const app = getApp();

Page({
  data: {
    titleTop: 0,
    titleHeight: 0,
    card: {},
    qrcode: '',
    avatar: '',
    imagePath: '',
    show: false,
    shareImage: ''
  },

  onLoad(options) {
    let menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      titleTop: menu.top + 2,
      titleHeight: menu.height,
      ...options
    });
    if (options.type === 'card') {
      if (options.from === 'index') {
        this.getMyCard();
      } else {
        this.getCard(options.cardId);
      };
    } else if (options.type === 'group') {
      this.getBasicInfo(options.groupId);
    };
  },

  onShareAppMessage() {
    if (this.data.type === 'card') {
      return {
        title: this.data.card.userName + '的快名片',
        path: `/pages/cardPreview/index?type=share&cardId=${this.data.card.cardId}`,
        imageUrl: this.data.shareImage
      }
    } else if (this.data.type === 'group') {
      return {
        title: this.data.groupInfo.title,
        path: `/pages/groupDetails/index?from=share&type=${this.data.from}&groupId=${this.data.groupId}`,
        imageUrl: this.data.shareImage
      }
    };
  },

  getCard(id) {
    getCardDetails(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        if (!new RegExp('https://').test(data.avatar) && !new RegExp('http://').test(data.avatar)) data.avatar = app.globalData.url;
        if (!new RegExp('https://').test(data.miniQrCode) && !new RegExp('http://').test(data.miniQrCode)) data.miniQrCode = app.globalData.url + data.miniQrCode;
        this.setData({
          card: data,
          qrcode: data.miniQrCode,
          avatar: data.avatar
        });
        setTimeout(() => {
          wx.getImageInfo({
            src: data.avatar,
            success: res => {
              let avatar = {
                path: res.path,
                width: res.width,
                height: res.height
              };
              this.canvasShareImage(avatar, data.userName, data.company, data.post ? data.post : '暂无', data.label);
            }
          });
        }, 500);
      };
    });
  },

  getMyCard() {
    getCardList({
      cardType: 1
    }).then(res => {
      if (res.data.code === 200) {
        let {
          rows,
          total
        } = res.data;
        if (total !== 0) {
          let card = rows.find(v => {
            if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
            if (!new RegExp('^https://').test(v.miniQrCode) && !new RegExp('^http://').test(v.miniQrCode)) v.miniQrCode = app.globalData.url + v.miniQrCode;
            return v.isDefault === 1
          });
          if (!card) card = rows[0];
          this.setData({
            card: card,
            qrcode: card.miniQrCode,
            avatar: card.avatar
          });
          setTimeout(() => {
            wx.getImageInfo({
              src: card.avatar,
              success: res => {
                let avatar = {
                  path: res.path,
                  width: res.width,
                  height: res.height
                };
                this.canvasShareImage(avatar, card.userName, card.company, card.post ? card.post : '暂无', card.label);
              }
            });
          }, 500);
        } else {
          wx.showToast({
            title: '您还没有名片',
            icon: 'none'
          });
        };
      };
    });
  },

  getBasicInfo(id) {
    groupQRcode(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        if (data.image !== '') data.image = !new RegExp('^https://').test(data.image) && !new RegExp('^http://').test(data.image) ? app.globalData.url + data.image : data.image;
        this.setData({
          groupInfo: data,
          avatar: data.image,
          qrcode: !new RegExp('https://').test(data.miniQrCode) && !new RegExp('http://').test(data.miniQrCode) ? app.globalData.url + data.miniQrCode : data.miniQrCode
        });
        setTimeout(() => {
          if (data.image) {
            wx.getImageInfo({
              src: data.image,
              success: res => {
                let avatar = {
                  path: res.path,
                  width: res.width,
                  height: res.height
                };
                this.groupCanvasShareImage(avatar, data.title);
              }
            });
          } else {
            wx.getImageInfo({
              src: '../../images/group_default_avatar.png',
              success: res => {
                let avatar = {
                  path: '/' + res.path,
                  width: res.width,
                  height: res.height
                };
                this.groupCanvasShareImage(avatar, data.title);
              }
            });
          };
        }, 500);
      };
    });
  },

  handleCanvas(e) {
    if (this.data.type === 'card') {
      console.log('名片打印第一步');
      wx.getImageInfo({
        src: this.data.avatar,
        success: avatar => {
          console.log('名片打印第二步');
          wx.getImageInfo({
            src: this.data.qrcode,
            success: qrcode => {
              console.log('名片打印第三步');
              this.canvasImage(avatar.path, this.data.card.userName, this.data.card.post, this.data.card.company, qrcode.path);
            }
          });
        }
      });
    } else if (this.data.type === 'group') {
      if (this.data.avatar === '') {
        wx.getImageInfo({
          src: this.data.qrcode,
          success: qrcode => {
            this.groupCanvasImage('', this.data.groupInfo.title, this.data.groupInfo.joinNum, qrcode.path);
          }
        });
      } else {
        wx.getImageInfo({
          src: this.data.avatar,
          success: avatar => {
            wx.getImageInfo({
              src: this.data.qrcode,
              success: qrcode => {
                this.groupCanvasImage(avatar.path, this.data.groupInfo.title, this.data.groupInfo.joinNum, qrcode.path);
              }
            });
          }
        });
      };
    };
  },

  // 生成分享小卡片
  canvasShareImage(avatar, userName, company, post, label) {
    let cvs = wx.createCanvasContext('share');
    cvs.drawImage('../../images/share_bg.png', 0, 0, 420, 336);
    cvs.save();
    cvs.beginPath();
    cvs.arc(210, 70, 54, 0, Math.PI * 2, false);
    cvs.clip();
    if (avatar.width > avatar.height) {
      cvs.drawImage(avatar.path, (avatar.width - avatar.height) / 2, 0, avatar.height, avatar.height, 156, 16, 108, 108);
    } else if (avatar.width < avatar.height) {
      cvs.drawImage(avatar.path, 0, (avatar.height - avatar.width) / 2, avatar.width, avatar.width, 156, 16, 108, 108);
    } else {
      cvs.drawImage(avatar.path, 156, 16, 108, 108);
    };
    cvs.restore();
    cvs.setFillStyle('#fff');
    cvs.setFontSize(26);
    let nameWidth = cvs.measureText(userName).width;
    cvs.fillText(userName, 210 - nameWidth / 2, 164);

    cvs.setFillStyle('#f7f7f7');
    cvs.setFontSize(20);
    let postWidth = cvs.measureText(`${company} · ${post}`).width;
    cvs.fillText(`${company} · ${post}`, 210 - postWidth / 2, 200);

    if (label.length > 0) {
      cvs.setFillStyle('#fff');
      cvs.setFontSize(22);
      label = label.map(v => {
        return {
          labelName: '#' + v,
          labelWidth: cvs.measureText('#' + v).width
        }
      }).sort((a, b) => b.labelWidth - a.labelWidth);
      let lineWidth = cvs.measureText('　|　').width;
      switch (label.length) {
        case 1:
          cvs.fillText(label[0].labelName, 210 - label[0].labelWidth / 2, 260);
          break;
        case 2:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          break;
        case 3:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName, 210 - (label[2].labelWidth) / 2, 300);
          break;
        case 4:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName + '　|　' + label[3].labelName, 210 - (label[2].labelWidth + label[3].labelWidth + lineWidth) / 2, 300);
          break;
        case 5:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName + '　|　' + label[3].labelName + '　|　' + label[4].labelName, 210 - (label[2].labelWidth + label[3].labelWidth + label[4].labelWidth + lineWidth * 2) / 2, 300);
          break;
        default:
          break;
      };
    };

    cvs.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'share',
        destWidth: '420',
        destHeight: '336',
        fileType: 'png',
        success: res => {
          this.setData({
            shareImage: res.tempFilePath
          });
        }
      });
    });
  },

  // 生成分享小卡片
  groupCanvasShareImage(avatar, groupName) {
    let cvs = wx.createCanvasContext('share');
    cvs.drawImage('../../images/share_bg.png', 0, 0, 420, 336);
    cvs.save();
    cvs.beginPath();
    cvs.arc(210, 136, 54, 0, Math.PI * 2, false);
    cvs.clip();
    if (avatar.width > avatar.height) {
      cvs.drawImage(avatar.path, (avatar.width - avatar.height) / 2, 0, avatar.height, avatar.height, 156, 82, 108, 108);
    } else if (avatar.width < avatar.height) {
      cvs.drawImage(avatar.path, 0, (avatar.height - avatar.width) / 2, avatar.width, avatar.width, 156, 82, 108, 108);
    } else {
      cvs.drawImage(avatar.path, 156, 82, 108, 108);
    };
    cvs.restore();
    cvs.setFillStyle('#fff');
    cvs.setFontSize(30);
    let nameWidth = cvs.measureText(groupName).width;
    cvs.fillText(groupName, 210 - nameWidth / 2, 240);

    cvs.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'share',
        destWidth: '420',
        destHeight: '336',
        fileType: 'png',
        success: res => {
          this.setData({
            shareImage: res.tempFilePath
          });
        }
      });
    });
  },

  // 生成图片
  canvasImage(avatar, userName, post, company, qrCode) {
    wx.showLoading({
      title: '生成中...',
      mask: true
    });
    console.log('名片打印第四步');
    let cvs = wx.createCanvasContext('canvas');
    cvs.setFillStyle('white');
    cvs.fillRect(0, 0, 325, 400);
    cvs.drawImage(avatar, 20, 20, 48, 48);
    cvs.setFillStyle('#333');
    cvs.setFontSize(16);
    let {
      width
    } = cvs.measureText(userName);
    cvs.fillText(userName, 80, 40);
    if (post) {
      cvs.setFontSize(12);
      cvs.setFillStyle('#999');
      cvs.fillText(post, width + 90, 40);
    };
    if (company) {
      cvs.setFontSize(12);
      cvs.fillText(company, 80, 62);
    };
    cvs.drawImage(qrCode, 32.5, 90, 260, 260);
    cvs.setFontSize(12);
    cvs.setFillStyle('#999');
    cvs.setTextAlign('center');
    cvs.fillText('扫描二维码，加我快名片', 162.5, 380);


    cvs.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        destWidth: '650',
        destHeight: '800',
        fileType: 'png',
        success: res => {
          console.log('名片打印第五步');
          console.log(res.tempFilePath);
          this.setData({
            imagePath: res.tempFilePath,
            show: true
          });
          wx.hideLoading({});
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: res => {
              wx.showToast({
                title: '保存成功',
                icon: 'success'
              });
            }
          });
        }
      });
    });
  },

  // 生成图片
  groupCanvasImage(avatar, name, num, qrCode) {
    wx.showLoading({
      title: '生成中...',
      mask: true
    });

    let cvs = wx.createCanvasContext('canvas');
    cvs.setFillStyle('white');
    cvs.fillRect(0, 0, 325, 400);
    cvs.drawImage(avatar ? avatar : '../../images/group_default_avatar.png', 24, 24, 40, 40);
    cvs.setFillStyle('#333');
    cvs.setFontSize(16);
    cvs.fillText(name, 92, 42);
    cvs.setFillStyle('#999');
    cvs.setFontSize(12);
    cvs.fillText(num + '人', 92, 60);
    cvs.drawImage(qrCode, 32.5, 90, 260, 260);
    cvs.setFontSize(12);
    cvs.setFillStyle('#999');
    cvs.setTextAlign('center');
    cvs.fillText('扫描二维码，加入群组', 162.5, 380);

    cvs.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        destWidth: '650',
        destHeight: '800',
        fileType: 'png',
        success: res => {
          if (res.errMsg === 'canvasToTempFilePath:ok') {
            this.setData({
              imagePath: res.tempFilePath,
              show: true
            });
            wx.hideLoading({})
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: res => {
                wx.showToast({
                  title: '保存成功',
                  icon: 'success'
                });
              }
            });
          };
        }
      });
    });
  },

  hideOverlay() {
    this.setData({
      show: false
    })
  },

  goback() {
    wx.navigateBack({
      delta: 1
    });
  }
})